package run.siyuan.rabbitmq.canal.consumer;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import run.siyuan.common.constant.rabbitmq.Constants;

import java.io.IOException;

@Slf4j
@Component
public class ConsumerService {

    @RabbitListener(queues = Constants.Queue.RABBITMQ_SIYUAN_CANAL_EXCHANGE_QUEUE, ackMode = "MANUAL")
    public void consumerMsg(String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        try {
            log.info("{} : Queue 收到的消息：{}", Constants.Queue.RABBITMQ_SIYUAN_CANAL_EXCHANGE_QUEUE, message);
            // RabbitMQ的ack机制中，第二个参数返回true，表示需要将这条消息投递给其他的消费者重新消费
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("异常:{}", e.getMessage());
            // 第三个参数true，表示这个消息会重新进入队列
            channel.basicNack(deliveryTag, false, false);
        }
    }

}
